"""
get real time data from s7 server
author:zjf
datetime:4-28
"""
import struct
from snap7 import client


class S7Client(object):
    def __init__(self, host, port, rack, slot):
        self._host = host
        self._port = port
        self._rack = rack
        self._slot = slot

    def read(self, area, dbnumber, start, size, format) -> tuple:
        """
        :param area: 0X81:I 0X82:Q 0X83:M 0X84:DB
        :param dbnumber:if 0X84 dbnumber = dbnumber else dbnumber = 1
        :param start: start byte
        :param size:  bytes
        :param format: this is a important parameter
        :return:
        """
        c = client.Client()
        try:
            c.connect(address=self._host, rack=self._rack, slot=self._slot, tcpport=self._port)
            temp = c.read_area(area=area, dbnumber=dbnumber, start=start, size=size)
            return self.handle_data(format, temp)
        except Exception as e:
            return ('error', e)
        finally:
            c.disconnect()

    def handle_data(self, format:str, raw_data:bytearray) -> tuple:
        res = struct.unpack(format,bytes(raw_data))
        return res


